package uebung04_h;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.MemoryImageSource;

import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class ResponseFunction {
	public static void main(String[] args) {
		
		final int w = 256, h = 256, pix[] = new int[w*h];
		
		final MemoryImageSource mis = new MemoryImageSource(w, h, pix, 0, w);
		
		mis.setAnimated(true);
		final JComponent canvas = new JComponent() {
			{setPreferredSize(new Dimension(w,h));}
			Image im = createImage(mis);
			@Override
			public void paint(Graphics g) {
				g.drawImage(im, 0, 0, this);
				System.out.println("dutu");
				super.paint(g);
			}
		};
		
		final JSlider sslider = new JSlider(JSlider.VERTICAL, 10, 100000, 10);
		final JSlider jslider = new JSlider(JSlider.HORIZONTAL, 1, 250, 1);
		
		ChangeListener cl = new ChangeListener() {
			final double scale = 50/(double)w;
			@Override
			public void stateChanged(ChangeEvent arg0) {
				double s = sslider.getValue()/1000., k = jslider.getValue()/1000.;
				for (int y = 0; y<h; y++) {
					for (int x = 0; x<w; x++) {
						
						double X = scale*x, Y = y*scale, tr = X+Y, det = X*Y;
						double r = (det-k*tr*tr)*s;
						
						int rgb = 0;
						
						if (r < 0)
							rgb = (((int)-r)&0xFF) | 0xFF000000;
						else
							rgb = ((((int)r)<<16)&0xFF0000) | ((((int)r)&0x00FF00)<<1) | 0xFF000000;
						pix[x+(h-y-1)*w] = rgb;
					}
				}
				mis.newPixels();
				canvas.repaint();
			}
		};
		
		sslider.addChangeListener(cl);
		jslider.addChangeListener(cl);
		
		JFrame ff = new JFrame();
		ff.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		ff.add(canvas, BorderLayout.CENTER);
		
		ff.add(sslider, BorderLayout.WEST);
		ff.add(jslider, BorderLayout.SOUTH);
		
		ff.pack();
		ff.setVisible(true);
	}
}
